import time
import threading
import maLogger
import datetime
import inspect
import json
import os
import sys

file_path = os.path.abspath(os.path.dirname(__file__))

class MaTasks:
    def __init__(self):
        self._logger = maLogger.maGetLogger('timer_task')
        self.time_thread = threading.Thread(target=self.time_task_entry, name="timer task")
        self._refresh_time()
        self.start_time = None
        self.stop_time = None
        self.max_time = datetime.datetime.strptime('23:59:59', '%H:%M:%S').time()
        self.doTask = None
        self.stopTask = None
        self.time_dict = dict()
        self.readFromSetting()

    def begin(self):
        self.time_thread.start()

    def getSetting(self):
        self.time_dict = dict()
        if((not self.start_time is None) and (not self.stop_time is None)):
            self.time_dict['startTime'] = "{0:0>2}:{1:0>2}".format(self.start_time.hour,self.start_time.minute)
            self.time_dict['stopTime'] = "{0:0>2}:{1:0>2}".format(self.stop_time.hour,self.stop_time.minute)
        else:
            self.time_dict['startTime'] = "00:00"
            self.time_dict['stopTime'] = "00:00"
        return json.dumps(self.time_dict)

    def time_task_entry(self):
        self._logger.info('start task')
        while True:
            self._refresh_time()
            if((not self.start_time is None) and (not self.stop_time is None)):
                if(self.start_time < self.stop_time):
                    if(self.now > self.start_time and self.now < self.stop_time):
                        self.time_task('do')
                    else:
                        self.time_task('stop')
                elif(self.start_time == self.stop_time):
                    #开始时间和结束时间相同则只在那一时刻执行
                    if(self.now == self.start_time):
                        self.time_task('do')
                else:
                    # 结束时间大于起始时间说明跨天了
                    if(self.now > self.start_time or self.now < self.stop_time):
                        self.time_task('do')
                    else:
                        self.time_task('stop')
            time.sleep(0.01)

    def _refresh_time(self):
        self.today = datetime.datetime.now()
        self.now = datetime.time(self.today.hour, self.today.minute, self.today.second)

    def setTime(self, start, stop):
        try:
            self._logger.info("set start time: {}, stop time: {}".format(start, stop))
            self.start_time = datetime.datetime.strptime(start, '%H:%M').time()
            self.stop_time = datetime.datetime.strptime(stop, '%H:%M').time()
            self.saveToSetting()
        except Exception as e:
            self._logger.error(e)

    def registerTask(self, callback, cmd):
        if inspect.ismethod(callback):
            if(cmd == 'do'):
                self._logger.info('do task registered')
                self.doTask = callback
            elif(cmd == 'stop'):
                self._logger.info('stop task registered')
                self.stopTask = callback
        else:
            self._logger.error('error type of callback')

    def time_task(self, cmd = 'do'):
        if(cmd == 'do'):
            if(not self.doTask is None):
                self.doTask()
                time.sleep(1)
        elif(cmd == 'stop'):
            if(not self.stopTask is None):
                self.stopTask()
                time.sleep(1)

    def readFromSetting(self):
        with open(file_path+"/setting.cfg", "r+") as cfg:
            st = cfg.readline()[0:5]
            sp = cfg.readline()[0:5]
            self.setTime(st, sp)
            cfg.close()

    def saveToSetting(self):
        self.getSetting()
        with open(file_path+"/setting.cfg", "w+") as cfg:
            cfg.write(self.time_dict['startTime']+'\n')
            cfg.write(self.time_dict['stopTime']+'\n')
            cfg.close()

class Mission:
    def __init__(self):
        self.do = self._do
        self.stop = self._stop

    def _do(self):
        print("doing")

    def _stop(self):
        print("stopping")

if __name__ == '__main__':
    mytask = MaTasks()
    mytask.begin()